/*
 * Author: Ray (qray686898@163.com)
 */

/**
 *
 * http配置
 *
 */

import axios from 'axios'
import store from '../store'
import router from '../router/router'
import { getToken, setToken, removeToken } from '@/util/auth'
import { Message } from 'element-ui'
import errorCode from '@/const/errorCode'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style


let instance = axios.create({});
// 超时时间
instance.defaults.timeout = 30000
// 跨域请求，允许保存cookie
instance.defaults.withCredentials = true
NProgress.configure({ showSpinner: false })
// HTTPrequest拦截
instance.interceptors.request.use(config => {
    NProgress.start() // start progress bar
    if (store.getters.access_token) {
        config.headers.sessionKey = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    }
    config.headers.post['Content-Type'] = 'application/json'
    return config
}, error => {
    return Promise.reject(error)
})
// HTTPresponse拦截
instance.interceptors.response.use(res => {
    NProgress.done()
    const data = res.data
    if (data.type) {
        return data
    } else {
        if (data.success) {
            return data.data
        } else {
            Message({
                message: data.msg,
                type: 'error'
            })
        }
    }

}, error => {
    NProgress.done()
    const errMsg = error.toString()
    const code = errMsg.substr(errMsg.indexOf('code') + 5)
    if (code === "802") {
        store.dispatch('FedLogOut').then(() => {
            router.push({ path: '/login', query: { redirect: router.currentRoute.fullPath } })
        })
    } else {
        Message({
            message: errorCode[code] || errorCode['default'],
            type: 'error'
        })
    }
    return Promise.reject(new Error(error))
})

export default instance
